<template>
  <view class="login-container">
    <!-- 验证码登录链接 -->
    <view class="verification-link">
      <text @click="switchToVerification">{{
        loginType === 'password' ? '验证码登录' : '密码登录'
      }}</text>
    </view>

    <!-- 主登录表单 -->
    <view class="login-form">
      <!-- 标题区域 -->
      <view class="title-section">
        <text class="main-title">{{ loginType === 'password' ? '密码登录' : '验证码登录' }}</text>
        <text class="subtitle">{{
          loginType === 'password' ? '登录发现更多精彩' : '首次登录自动注册'
        }}</text>
      </view>

      <!-- 输入区域 -->
      <view class="input-section">
        <!-- 账号/手机号输入框 -->
        <view class="input-group">
          <input v-model="account" :placeholder="loginType === 'password' ? '请输入账号' : '请输入手机号'" class="input-field" />
          <text v-if="loginType === 'password'" class="register-link" @click="goToRegister">去注册</text>
        </view>

        <!-- 密码/验证码输入框 -->
        <view class="input-group">
          <input v-model="password" :placeholder="loginType === 'password' ? '请输入密码' : '请输入验证码'"
            :type="loginType === 'password' ? 'password' : 'text'" class="input-field" />
          <text v-if="loginType === 'verification'" class="get-code-btn" :class="{ disabled: countdown > 0 }"
            @click="getVerificationCode">
            {{ countdown > 0 ? `${countdown}s` : '获取验证码' }}
          </text>
        </view>
      </view>

      <!-- 协议同意区域 -->
      <view class="agreement-section">
        <view class="agreement-item">
          <view class="checkbox" :class="{ checked: isAgreed }" @click="toggleAgreement">
            <view class="checkbox-dot" v-if="isAgreed"></view>
          </view>
          <text class="agreement-text">已阅读并同意</text>
          <text class="agreement-link" @click="showUserAgreement">用户注册协议</text>
          <text class="agreement-text">和</text>
          <text class="agreement-link" @click="showPrivacyPolicy">隐私协议</text>
        </view>
      </view>

      <!-- 登录按钮 -->
      <button class="login-button" @click="handleLogin" :disabled="!isAgreed">
        {{ loginType === 'password' ? '登录' : '验证并登录' }}
      </button>

      <!-- 忘记密码链接 -->
      <view v-if="loginType === 'password'" class="forgot-password">
        <text @click="forgotPassword">忘记密码?</text>
      </view>
    </view>

    <!-- 其他登录方式 -->
    <view class="other-login">
      <view class="divider">
        <text class="divider-text">其他登录方式</text>
      </view>
      <view class="wechat-login" @click="wechatLogin">
        <view class="wechat-icon">
          <text class="wechat-text">微信</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRequest } from '@/api'
import { TokenManager } from '@/utils/token'
import { UserInfoManager } from '@/utils/userInfo'
import { useOutsideAppStore } from '@/store/app'
const { API_LOGIN_POST, API_SMS_SEND, API_MOBILELOGIN_POST, API_WEIXIN_POST } = useRequest()
const appStore = useOutsideAppStore()
// 响应式数据
const loginType = ref('password') // 默认显示验证码登录
const account = ref('')
// const account = ref('13811454485')
const password = ref('')
const isAgreed = ref(false)
const countdown = ref(0)

// 切换登录方式
function switchToVerification() {
  loginType.value = loginType.value === 'password' ? 'verification' : 'password'
  password.value = ''
}

// 获取验证码
async function getVerificationCode() {
  if (!account.value) {
    uni.showToast({ title: '请输入手机号', icon: 'none' })
    return
  }

  if (countdown.value > 0) {
    return
  }

  try {
    uni.showLoading({ title: '发送中...' })

    const params = {
      mobile: account.value,
      event: 'mobilelogin' // 登录验证码类型
    }

    const res = await API_SMS_SEND(params)

    if (res.code === 1) {
      uni.showToast({ title: '验证码已发送', icon: 'success' })

      // 开始倒计时
      countdown.value = 60
      const timer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    } else {
      uni.showToast({ title: res.msg || '发送失败', icon: 'none' })
    }
  } catch (error) {
    uni.showToast({ title: '发送失败，请重试', icon: 'none' })
  } finally {
    uni.hideLoading()
  }
}

// 切换协议同意状态
function toggleAgreement() {
  isAgreed.value = !isAgreed.value
}

// 去注册
function goToRegister() {
  uni.navigateTo({ url: '/pages/login/register' })
}

// 显示用户协议
function showUserAgreement() {
  uni.navigateTo({
    url: '/user/mine/UserAgreement'
  })
}

// 显示隐私协议
function showPrivacyPolicy() {
  uni.navigateTo({
    url: '/user/mine/toLegalTerms'
  })
}

// 忘记密码
function forgotPassword() {
  uni.navigateTo({ url: '/pages/login/forgot' })
}

// 微信登录（App：通过 code 获取 access_token）
async function wechatLogin() {
  try {
    const providers: any = await new Promise((resolve, reject) => {
      uni.getProvider({ service: 'oauth', success: resolve, fail: reject })
    })
    if (!providers.provider || !providers.provider.includes('weixin')) {
      uni.showToast({ title: '未检测到微信授权', icon: 'none' })
      return
    }
    uni.showLoading({ title: '微信登录中...' })
    const loginRes: any = await new Promise((resolve, reject) => {
      uni.login({ provider: 'weixin', success: resolve, fail: reject })
    })
    const code = loginRes.code
    if (!code) {
      uni.showToast({ title: '获取微信code失败', icon: 'none' })
      return
    }
    const params = { platform: 'weixin', code }
    const res = await API_WEIXIN_POST(params)
    if (res.code === 1) {
      TokenManager.setToken(res.data.token)
      UserInfoManager.setUserInfo(res.data.userinfo)
      appStore.setUserInfo(res.data.userinfo)
      if (res.data.userinfo.isdriver === 1) {
        uni.reLaunch({ url: '/driver/orderHall/index' })
      } else {
        uni.reLaunch({ url: '/user/home/index' })
      }
    }
  } catch (error) {
    
  } finally {
    uni.hideLoading()
  }
}

// 登录处理
const handleLogin = async () => {
  if (!account.value) {
    uni.showToast({
      title: loginType.value === 'password' ? '请输入账号' : '请输入手机号',
      icon: 'none'
    })
    return
  }

  if (!password.value) {
    uni.showToast({
      title: loginType.value === 'password' ? '请输入密码' : '请输入验证码',
      icon: 'none'
    })
    return
  }

  if (!isAgreed.value) {
    uni.showToast({ title: '请先同意用户协议', icon: 'none' })
    return
  }

  try {
    uni.showLoading({ title: '登录中...' })

    // 根据登录类型构建不同的参数
    const params = loginType.value === 'password'
      ? {
        account: account.value,
        password: password.value
      }
      : {
        mobile: account.value,
        captcha: password.value // 验证码
      }

    const res = await (loginType.value === 'password'
      ? API_LOGIN_POST(params)
      : API_MOBILELOGIN_POST(params))
  
    if (res.code === 1) {
      TokenManager.setToken(res.data.token)
      UserInfoManager.setUserInfo(res.data.userinfo)
      appStore.setUserInfo(res.data.userinfo)

      if (res.data.userinfo.isdriver === 1) {
        uni.reLaunch({ url: '/driver/orderHall/index' })
      } else {
        uni.reLaunch({ url: '/user/home/index' })
      }
    }
  } catch (error) {
    
  } finally {
    uni.hideLoading()
  }
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  background: #fff;
  padding: 40rpx 60rpx;
  position: relative;
}

/* 验证码登录链接 */
.verification-link {
  position: absolute;
  top: 60rpx;
  right: 60rpx;
}

.verification-link text {
  color: #ff6b35;
  font-size: 28rpx;
}

/* 主登录表单 */
.login-form {
  margin-top: 120rpx;
}

/* 标题区域 */
.title-section {
  margin-bottom: 80rpx;
}

.main-title {
  display: block;
  font-size: 48rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 16rpx;
}

.subtitle {
  display: block;
  font-size: 28rpx;
  color: #999;
}

/* 输入区域 */
.input-section {
  margin-bottom: 60rpx;
}

.input-group {
  position: relative;
  margin-bottom: 40rpx;
  background: #f5f5f5;
  border-radius: 12rpx;
  padding: 0 24rpx;
  height: 88rpx;
  display: flex;
  align-items: center;
}

.input-field {
  flex: 1;
  height: 100%;
  font-size: 32rpx;
  background: transparent;
  border: none;
  outline: none;
}

.register-link {
  color: #ff6b35;
  font-size: 28rpx;
  margin-left: 20rpx;
}

.get-code-btn {
  color: #ff6b35;
  font-size: 28rpx;
  margin-left: 20rpx;
  white-space: nowrap;
  cursor: pointer;
}

.get-code-btn.disabled {
  color: #999;
  cursor: not-allowed;
}

/* 协议同意区域 */
.agreement-section {
  margin-bottom: 60rpx;
}

.agreement-item {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.checkbox {
  width: 32rpx;
  height: 32rpx;
  border-radius: 50%;
  border: 2rpx solid #ff6b35;
  margin-right: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
}

.checkbox.checked {
  background: #ff6b35;
}

.checkbox-dot {
  width: 16rpx;
  height: 16rpx;
  border-radius: 50%;
  background: #fff;
}

.agreement-text {
  font-size: 28rpx;
  color: #333;
  margin-right: 8rpx;
}

.agreement-link {
  font-size: 28rpx;
  color: #ff6b35;
  margin-right: 8rpx;
}

/* 登录按钮 */
.login-button {
  width: 100%;
  height: 88rpx;
  background: #ff6b35;
  color: #fff;
  font-size: 32rpx;
  border-radius: 12rpx;
  border: none;
  margin-bottom: 40rpx;
}

.login-button:disabled {
  background: #ccc;
}

/* 忘记密码 */
.forgot-password {
  text-align: center;
  margin-bottom: 80rpx;
}

.forgot-password text {
  color: #333;
  font-size: 28rpx;
}

/* 其他登录方式 */
.other-login {
  margin-top: 80rpx;
}

.divider {
  position: relative;
  text-align: center;
  margin-bottom: 60rpx;
}

.divider::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  height: 1rpx;
  background: #e5e5e5;
  z-index: 1;
}

.divider-text {
  background: #fff;
  padding: 0 40rpx;
  color: #999;
  font-size: 28rpx;
  position: relative;
  z-index: 2;
}

.wechat-login {
  display: flex;
  justify-content: center;
}

.wechat-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background: #07c160;
  display: flex;
  align-items: center;
  justify-content: center;
}

.wechat-text {
  color: #fff;
  font-size: 24rpx;
}
</style>
